package com.vibrationkeyboard.app

import android.app.Application
import android.util.Log
import com.vibrationkeyboard.app.utils.Logger

class VibrationKeyboardApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        Logger.i("VibrationKeyboardApplication onCreate")
        
        // 初始化应用
        initializeApp()
    }

    override fun onTerminate() {
        super.onTerminate()
        Logger.i("VibrationKeyboardApplication onTerminate")
    }

    override fun onLowMemory() {
        super.onLowMemory()
        Logger.w("VibrationKeyboardApplication onLowMemory")
    }

    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
        Logger.w("VibrationKeyboardApplication onTrimMemory: $level")
    }

    private fun initializeApp() {
        try {
            // 初始化日志系统
            Logger.i("Initializing Vibration Keyboard Application")
            
            // 检查设备兼容性
            checkDeviceCompatibility()
            
            // 初始化设置
            initializeSettings()
            
            Logger.i("Vibration Keyboard Application initialized successfully")
            
        } catch (e: Exception) {
            Logger.e("Error initializing application", e)
        }
    }

    private fun checkDeviceCompatibility() {
        // 检查设备是否支持所需传感器
        val sensorManager = getSystemService(SENSOR_SERVICE) as android.hardware.SensorManager
        
        val accelerometer = sensorManager.getDefaultSensor(android.hardware.Sensor.TYPE_ACCELEROMETER)
        val gyroscope = sensorManager.getDefaultSensor(android.hardware.Sensor.TYPE_GYROSCOPE)
        
        if (accelerometer == null) {
            Logger.w("Accelerometer not available on this device")
        } else {
            Logger.i("Accelerometer available: ${accelerometer.name}")
        }
        
        if (gyroscope == null) {
            Logger.w("Gyroscope not available on this device")
        } else {
            Logger.i("Gyroscope available: ${gyroscope.name}")
        }
    }

    private fun initializeSettings() {
        // 初始化默认设置
        val sharedPrefs = getSharedPreferences("vibration_keyboard_settings", MODE_PRIVATE)
        
        if (!sharedPrefs.contains("sample_rate")) {
            sharedPrefs.edit().apply {
                putInt("sample_rate", 100)
                putInt("sensor_delay", 1)
                putBoolean("vibration_feedback", true)
                putBoolean("auto_correct", false)
                putBoolean("sound_feedback", false)
                apply()
            }
            Logger.i("Default settings initialized")
        }
    }
} 